<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8"/>
    <title>STOMP 聊天室（/topic 房间广播，/user/queue 私信）</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <style>
        body {
            font-family: system-ui, Arial;
            margin: 20px
        }

        #log {
            border: 1px solid #ddd;
            height: 50vh;
            overflow: auto;
            padding: 8px;
            margin: 10px 0
        }

        input, button {
            padding: 8px
        }

        .sys {
            color: #888
        }

        .me {
            color: #0b73ee
        }
    </style>
</head>
<body>
<h3>STOMP 聊天室</h3>

<div>
    用户：<input id="user" value="Alice">
    <button id="btnConn">连接</button>
    <button id="btnDisc" disabled>断开</button>
</div>

<div id="log"></div>

<div>
    房间：<input id="room" value="room-1">
    <button id="btnJoin" disabled>加入</button>
    <button id="btnLeave" disabled>离开</button>
</div>

<div style="margin-top:6px">
    <input id="msg" style="width:60%" placeholder="发送到房间">
    <button id="btnSend" disabled>发送</button>
</div>

<div style="margin-top:6px">
    私聊对象：<input id="to" placeholder="Bob">
    <input id="pmsg" style="width:50%" placeholder="私聊内容">
    <button id="btnWhisper" disabled>私信</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/sockjs-client/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs/lib/stomp.min.js"></script>
<script>
    let stomp = null;
    let subRoom = null;

    const $ = id => document.getElementById(id);
    const log = html => {
        const d = document.createElement('div');
        d.innerHTML = html;
        $('log').appendChild(d);
        $('log').scrollTop = $('log').scrollHeight;
    };

    $('btnConn').onclick = () => {
        const user = $('user').value.trim() || 'Guest';
        const sock = new SockJS(`/ws?user=${encodeURIComponent(user)}`);
        stomp = Stomp.over(sock);
        stomp.debug = () => {
        }; // 关闭调试日志
        stomp.connect({}, frame => {
            log(`<span class="sys">[system] connected as ${user}</span>`);
            // 订阅个人队列（接收私信）
            stomp.subscribe("/user/queue/personal", msg => {
                const m = JSON.parse(msg.body);
                log(`<span class="me">[whisper ${m.from}]</span> ${m.content}`);
            });
            toggle(true);
        }, err => log(`<span class="sys">[error] ${err}</span>`));
    };

    $('btnDisc').onclick = () => {
        if (stomp) {
            stomp.disconnect(() => log('<span class="sys">[system] disconnected</span>'));
        }
        toggle(false);
    };

    $('btnJoin').onclick = () => {
        const roomId = $('room').value.trim();
        if (!roomId) return;
        // 订阅房间广播
        subRoom && subRoom.unsubscribe();
        subRoom = stomp.subscribe(`/topic/room/${roomId}`, msg => {
            const m = JSON.parse(msg.body);
            if (m.type === 'CHAT') log(`<span class="me">[${m.from} @${m.roomId}]</span> ${m.content}`);
            if (m.type === 'JOIN' || m.type === 'LEAVE') log(`<span class="sys">[system] ${m.content}</span>`);
        });
        // 通知加入
        stomp.send(`/app/room/${roomId}/join`, {}, JSON.stringify({}));
    };

    $('btnLeave').onclick = () => {
        const roomId = $('room').value.trim();
        if (!roomId) return;
        stomp.send(`/app/room/${roomId}/leave`, {}, JSON.stringify({}));
        subRoom && subRoom.unsubscribe();
        subRoom = null;
    };

    $('btnSend').onclick = () => {
        const roomId = $('room').value.trim();
        const content = $('msg').value.trim();
        if (!roomId || !content) return;
        stomp.send(`/app/room/${roomId}/send`, {}, JSON.stringify({content}));
        $('msg').value = '';
    };

    $('btnWhisper').onclick = () => {
        const to = $('to').value.trim();
        const content = $('pmsg').value.trim();
        if (!to || !content) return;
        stomp.send(`/app/whisper`, {}, JSON.stringify({to, content}));
        $('pmsg').value = '';
    };

    function toggle(ok) {
        $('btnConn').disabled = ok;
        $('btnDisc').disabled = !ok;
        $('btnJoin').disabled = !ok;
        $('btnLeave').disabled = !ok;
        $('btnSend').disabled = !ok;
        $('btnWhisper').disabled = !ok;
    }
</script>
</body>
</html>